package utils;


import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DButils {  //连接和关闭数据库的方法类
    public static Connection getConnection(){  //获得连接数据库的Connection的对象   静态方法,直接通过类名.方法名称调用
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/furniture?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("zcwa");
        try {
            Connection connection= (Connection) dataSource.getConnection();
            return connection;//返回连接的Connection对象
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void close(java.sql.Connection conn, Statement st, ResultSet rs){  //关闭连接资源   ResultSet是查询的时候打开的资源
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
